import config from '../common/config'
let baseUrl = config.API_URL;
let urls;
let queryString;
let second = 2000; // 几秒内同一个请求只能调用一次
const cache = new Map()
function request(method, url, params) {
  let options = {
    method,
    headers: { "Content-Type": "application/json" },
  };
  switch (true) {
    case method === "POST":
      urls = baseUrl + url;
      options.body = JSON.stringify(params);
    case method === "GET":
      queryString = params
        ? Object.keys(params)
          .map((key) => `${key}=${params[key]}`)
          .join("&")
        : "";
      urls = params ? baseUrl + url + "?" + queryString : baseUrl + url;
    default:
      console.log('请求失败');
  }
  const nowTime = Date.now();//  获取当前时间戳
  // 检查此URL是否有缓存的promise
  if (cache.has(url)) {
    // 检查数组里是否有url接口
    const { promise, timestamp } = cache.get(url);
    const timeElapsed = nowTime - timestamp;
    // 如果缓存的promise仍在配置(几秒)的窗口内，则返回相同的promise,不调用接口
    if (timeElapsed < second) {
      return promise;
    }
    // 如果(几秒)窗口已过，则使缓存无效并发出新请求
    cache.delete(url);
  }else{
    let data  = fetchData(urls, options); // 请求接口
    cache.set(url, { promise: data, timestamp: nowTime });
    setTimeout(() => {
      cache.delete(url);
    }, second); // 1秒后清除缓存
    return data;
  }
 
}
function fetchData(url, params) {
  return new Promise((resolve, reject) => {
    fetch(url, params)
      .then((res) => res.json())
      .then((data) => {
        if (data.code = 200) {
          resolve(data)
        } else {
          reject(data)
        }
      })
      .catch((err) => reject(err));
  });
}
// export default request;

export default {
  get: (url, params = {}) => {
    let method = "GET"
    return request(method, url, params);
  },
  post: (url, params = {}) => {
    let method = "POST"
    return request(method, url, params);
  },
};
